package com.example.demo;

import com.example.demo.statemachine.demo02.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import java.net.InetAddress;

/**
 * @author MarioZzz
 */
@Slf4j
@SpringBootApplication()
@MapperScan("com.example.demo.mapper")
public class DemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
        outPutAppUrl(applicationContext);

        stateMachineTest(applicationContext);
    }

    private static void stateMachineTest(ConfigurableApplicationContext applicationContext) {
        Thread.currentThread().setName("主线程");

        IOrderService orderService = (IOrderService) applicationContext.getBean("orderService");

        orderService.create();
        orderService.create();

        orderService.pay(1);

        new Thread("客户线程") {
            @Override
            public void run() {
                orderService.deliver(1);
                orderService.receive(1);
            }
        }.start();

        orderService.pay(2);
        orderService.deliver(2);
        orderService.receive(2);

        System.out.println("全部订单状态：" + orderService.getOrders());
    }

    private static void outPutAppUrl(ConfigurableApplicationContext application) {
        try {
            Environment env = application.getEnvironment();
            String ip = InetAddress.getLocalHost().getHostAddress();

            String port = env.getProperty("server.port");
            String property = env.getProperty("server.servlet.context-path");
            String path = property == null ? "" : property;
            log.warn(
                    "\n\t" +
                            "----------------------------------------------------------\n\t" +
                            "Application is running success! Access URLs:\n\t" +
                            "Local: \t\thttp://localhost:" + port + path + "/\n\t" +
                            "External: \thttp://" + ip + ":" + port + path + "/\n\t" +
                            "knife4j: \thttp://" + ip + ":" + port + path + "/doc.html\n\t" +
                            "swagger: \thttp://" + ip + ":" + port + path + "/swagger-ui.html\n\t" +
                            "------------------------------------------------------------");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
